package com.zb.frame.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zb.frame.base.model.MPPage;
import com.zb.frame.base.utils.encrypt.SimpleHashUtil;
import com.zb.frame.modules.sys.entity.RelUserRole;
import com.zb.frame.modules.sys.entity.User;
import com.zb.frame.modules.sys.mapper.MenuMapper;
import com.zb.frame.modules.sys.mapper.RelUserRoleMapper;
import com.zb.frame.modules.sys.mapper.UserMapper;
import com.zb.frame.modules.sys.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bangZZ
 * @since 2020-06-04
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    RelUserRoleMapper relUserRoleMapper;

    @Autowired
    MenuMapper menuMapper;

    /**
     * 根据用户登录账号获取[用户](User)信息
     * @param username 用户登录账号
     * @return User
     */
    @Override
    public User getUserByUsername(String username) {
        return userMapper.getUserByName(username);
    }

    /**
     *根据用户Id获取用户的状态(0-停用/1-正常/2-上锁)和角色列表
     * @param userId 用户Id
     * @return {"state":XXX,"roles":['XXX','XXX',...]}
     */
    @Override
    public Map<String, Object> getUserStateAndRoles(Long userId) {
        Map<String, Object> ret = new HashMap<>();
        List<Map<String, Object>> list = userMapper.getUserStateAndRoles(userId);
        Set<String> roleList = new HashSet<>();
        Integer state = 0;
        if (list.size() > 0){
            for (Map<String, Object> map : list) {
                state = (Integer) map.get("state");
                roleList.add((String) map.get("role"));
            }
            ret.put("state", state);
            ret.put("roles", roleList);
        }
        return ret;
    }

    /**
     * 修改用户密码
     * @param user
     * @return
     */
    @Override
    public boolean updatePassword(User user) {
        return userMapper.updateById(user) > 0;
    }

    /**
     * 获取用户列表 分页
     * @param params
     * @return
     */
    @Override
    public MPPage getUserList(Page<User> pageInfo, Map<String, Object> params) {
        Integer currPage = (params.get("page") == null) ? 1 : (Integer)params.get("page");
        Integer pageSize = params.get("limit") == null ? 10 : (Integer)params.get("limit");
        QueryWrapper<User> wrapper = new QueryWrapper().select("user_id","user_name","user_alias","user_status","user_sex","user_phone","user_email","create_time","user_desc");
        wrapper.ne("user_id",1);// 过滤掉超级管理员
        if (params.get("type") != null) {
            wrapper.eq("user_status", (Integer)params.get("type"));
        }
        if (StringUtils.isNotBlank((String)params.get("name"))) {
            wrapper.and(qw -> qw.like("user_name", params.get("name")).or().like("user_alias", params.get("name")));
        }
        return new MPPage(this.page(pageInfo, wrapper));
    }


    /**
     * 根据用户Id获取用户信息
     * @param id
     * @return
     */
    @Override
    public User getUser(Long id) {
        QueryWrapper<User> wrapper = new QueryWrapper().select("user_id","user_name","user_alias","user_status","user_sex","user_phone","user_email","user_avatar","user_desc");
        wrapper.eq("user_id", id);
        User user = this.getOne(wrapper);
        List<RelUserRole> roleInfo = relUserRoleMapper.getRoleInfoByUserId(id);
        List<String> role = new ArrayList<>();
        for (RelUserRole obj : roleInfo) {
            role.add(obj.getRoleName());
        }
        user.setRoleNames(role);
        return user;
    }

    @Override
    public boolean isExistUserName(User user) {
        QueryWrapper<User> wrapper = new QueryWrapper<User>();
        wrapper.eq("user_name", user.getUserName());
        return this.count(wrapper) > 0;
    }

    @Override
    public User addUser(User data, Long createId) {
        User user = new User();
        user.setUserName(data.getUserName());
        user.setUserAlias(data.getUserAlias());
        user.setUserPassword(SimpleHashUtil.encode(data.getUserPassword()));
        user.setUserPhone(data.getUserPhone());
        user.setUserEmail(data.getUserEmail());
        user.setUserSex(data.getUserSex());
        user.setUserAvatar("");
        user.setUserDesc(data.getUserDesc());
        user.setCreateUser(createId);
        this.save(user);
        return (user.getUserId()  != null) ? user : null;
    }

    @Override
    public User updateUser(User user, User data) {
        user.setUserName(data.getUserName());
        user.setUserAlias(data.getUserAlias());
        user.setUserPhone(data.getUserPhone());
        user.setUserEmail(data.getUserEmail());
        user.setUserSex(data.getUserSex());
        user.setUserAvatar("");
        user.setUserDesc(data.getUserDesc());
        boolean f = this.updateById(user);
        return f ? user : null;
    }

    @Override
    public boolean changeStatus(Long userId, Integer status) {
        User user = new User();
        user.setUserId(userId);
        user.setUserStatus(status);
        return this.updateById(user);
    }
}
